package com.example.administrator.hqq.utils;

//import android.content.Context;
//import android.util.Log;
//
//import org.eclipse.paho.android.service.MqttAndroidClient;
//
//import java.nio.charset.Charset;
//import java.security.InvalidKeyException;
//import java.security.NoSuchAlgorithmException;
//
//import javax.crypto.Mac;
//import javax.crypto.spec.SecretKeySpec;
//
//import static org.eclipse.paho.client.mqttv3.MqttConnectOptions.MQTT_VERSION_3_1_1;

import org.apache.commons.codec.binary.Base64;

import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @name: HQQ
 * @describe:
 * @author: 康海涛 QQ2541849981
 * @time: 2019/3/4 19:18
 * @remark:
 */
public class MqttUtils {
//    private final String TAG = this.getClass().getSimpleName();
//    private static MqttUtils mqttUtils;
//    MqttAndroidClient mqttAndroidClient;
//    final String serverUri = "tcp://mqtt-cn-0pp10tegi02.mqtt.aliyuncs.com:1883";
//    final String groupId = "GID_app_1";
//    final String topic = "HQQ_1";
//    final Boolean cleanSession =false;
//    String instanceId="mqtt-cn-0pp10tegi02";
//    String clientId = groupId+ "@@@6773";
//    String accessKey = "LTAIW690HSRuiWsr";
//    String secretKey = "YwYeLbmcUkxqh7S8YVkLeYvMkufuom";
//    public static MqttUtils getInstance(){
//        if (mqttUtils==null)
//        {
//            mqttUtils=new MqttUtils();
//        }
//        return mqttUtils;
//    }
//
//    public MqttAndroidClient getMqttAndroidClient() {
//        return mqttAndroidClient;
//    }
//
//    public void initMqtt(Context context){
//        mqttAndroidClient = new MqttAndroidClient(context.getApplicationContext(), serverUri, clientId);
//        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
//            @Override
//            public void connectComplete(boolean reconnect, String serverURI) {
//                if (reconnect) {
//                    Log.e(TAG, "重新连接connectComplete: ");
//                } else {
//                }
//                Log.e(TAG, "重新连接完成connectComplete: ");
//            }
//
//            @Override
//            public void connectionLost(Throwable cause) {
//                Log.e(TAG,"连接失败信息"+cause.toString());
//            }
//
//            @Override
//            public void messageArrived(String topic, MqttMessage message) throws Exception {
//                Log.e(TAG,"接收的消息Incoming message: " + new String(message.getPayload()));
//            }
//
//            @Override
//            public void deliveryComplete(IMqttDeliveryToken token) {
//
//            }
//        });
//        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
//        String sign = null;
//        try {
//            sign = macSignature(clientId, secretKey);
//        } catch (InvalidKeyException e) {
//            e.printStackTrace();
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        Log.e(TAG, "sign: "+sign );
//        Log.e("TAG", "onCreate: "+"Signature"+"|"+accessKey+"|"+instanceId );
//        mqttConnectOptions.setUserName("Signature"+"|"+accessKey+"|"+instanceId);
//        mqttConnectOptions.setPassword(sign.toCharArray());
//        mqttConnectOptions.setCleanSession(cleanSession);
//        mqttConnectOptions.setKeepAliveInterval(90);
//        mqttConnectOptions.setAutomaticReconnect(true);
//        mqttConnectOptions.setMqttVersion(MQTT_VERSION_3_1_1);
//        try {
//            //addToHistory("Connecting to " + serverUri);
//            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
//                @Override
//                public void onSuccess(IMqttToken asyncActionToken) {
//                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
//                    disconnectedBufferOptions.setBufferEnabled(true);
//                    disconnectedBufferOptions.setBufferSize(100);
//                    disconnectedBufferOptions.setPersistBuffer(false);
//                    disconnectedBufferOptions.setDeleteOldestMessages(false);
//                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
//                    Log.e(TAG, "链接成功onSuccess: ");
//                }
//
//                @Override
//                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
////                    addToHistory("Failed to connect to: " + serverUri);
//                    Log.e(TAG,"链接失败+++"+exception.toString());
//                }
//            });
//        } catch (MqttException ex){
//            ex.printStackTrace();
//        }
//    }
//
    /**
     * @param text      要签名的文本
     * @param secretKey 阿里云MQ secretKey
     * @return 加密后的字符串
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     */
    public static String macSignature(String text, String secretKey) throws InvalidKeyException, NoSuchAlgorithmException {
        Charset charset = Charset.forName("UTF-8");
        String algorithm = "HmacSHA1";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(secretKey.getBytes(charset), algorithm));
        byte[] bytes = mac.doFinal(text.getBytes(charset));
        return new String(Base64.encodeBase64(bytes), charset);
    }
}
